<template>
  <div class="account-manage-page pd16" v-loading="pageLoading">
    <el-card class="box-card">
      <div class="search-block">
        <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
          <el-row :gutter="16">
            <!-- <el-col :span="8">
              <el-form-item label="所属项目：" prop="organ">
                <el-tree-select
                  v-model="searchParams.organ"
                  node-key="pid"
                  :data="treeData"
                  :props="defaultProps"
                  :render-after-expand="false"
                  check-strictly
                  clearable
                  placeholder="请选择所属项目"
                  style="width: 100%;"/>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="用户姓名：" prop="name">
                <el-input v-model="searchParams.name" clearable placeholder="请输入用户姓名" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户账号：" prop="account">
                <el-input v-model="searchParams.account" clearable placeholder="请输入用户账号" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码：" prop="phone">
                <el-input v-model="searchParams.phone" clearable placeholder="请输入手机号码" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button @click="reset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="btn-group">
        <el-button type="primary" @click="addAccount">新建账号</el-button>
      </div>

      <div ref="tableBlockRef" class="data-block mt16 table-block">
        <el-table :data="tableData" :max-height="tableHeight" class="nr-table">
          <el-table-column label="姓名" prop="userAlias"></el-table-column>
          <el-table-column label="账号" prop="username"></el-table-column>
          <el-table-column label="手机号码" prop="phoneNum"></el-table-column>
          <el-table-column label="电子邮箱" prop="email"></el-table-column>
          <el-table-column label="所属项目" prop="projectName"></el-table-column>
          <el-table-column label="角色" prop="roleName"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link class="table-btn" type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
              <el-link class="table-btn" type="warning" :underline="false" @click="handleResetPwd(scope.row)">重置密码</el-link>
              <el-link class="table-btn" type="danger" :underline="false" @click="handleDelete(scope.row)">注销</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-right-block">
        <el-pagination
          class="nr-page"
          v-model:current-page="searchParams.currentPage"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          layout="total, prev, pager, next, sizes, jumper"
          :total="searchParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <account-modify-form
      :dialogVisible="modifyFormVis"
      :formStatus="modifyFormStatus"
      :formData="accountFormData.data"
      @update:dialogVisible="(value: boolean) => modifyFormVis = value"
      @submit="getAccountData">
    </account-modify-form>
  </div>
</template>

<script setup lang="ts" name="AccountManage">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import AccountModifyForm from './account-modify-form.vue'
import { accountListPage, accountDelete, accountUpdate, pwdReset } from '@/api/account-manage'
import { projectList } from '@/api/project-manage'

const pageLoading = ref(false)
const defaultProps = {
  children: 'projectTree',
  label: 'projectName'
}
const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  organ: '',
  name: '',
  account: '',
  phone: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const treeData = ref<any>([])
const tableData = ref<any>([])
const tableBlockRef = ref<any>(null)
const tableHeight = ref(200)
const modifyFormVis = ref(false)
const modifyFormStatus = ref(0)
const accountFormData = ref({
  data: {}
})

onMounted(() => {
  resizeTable()
  window.addEventListener('resize', resizeTable, false)
  getProjectData()
  getAccountData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeTable, false)
})

// 窗口改变table高度
const resizeTable = () => {
  tableHeight.value = tableBlockRef.value.offsetHeight
}

// 查询
const search = () => {
  searchParams.currentPage = 1
  getAccountData()
}

// 重置
const reset = () => {
  searchParamsRef.value?.resetFields()
}

// 分页跳转
const handleCurrentChange = (val: number) => {
  getAccountData()
}
const handleSizeChange = (val: number) => {
  getAccountData()
}

// 新建
const addAccount = () => {
  modifyFormVis.value = true
  modifyFormStatus.value = 0
}

// 编辑
const handleEdit = (row: any) => {
  modifyFormVis.value = true
  modifyFormStatus.value = 1
  accountFormData.value.data = Object.assign({}, row)
}

// 重置密码
const handleResetPwd = (row: any) => {
  ElMessageBox.confirm(
    `确定要重置【${row.username}】密码吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      id: row.id
    }
    pwdReset(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`重置成功！`)
        getAccountData()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 注销
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要注销【${row.username}】吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      id: row.id
    }
    accountDelete(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`删除成功！`)
        getAccountData()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 获取用户表格数据
const getAccountData = async () => {
  let params = {
    userAlias: searchParams.name,
    username: searchParams.account,
    phoneNum: searchParams.phone,
    currentPage: searchParams.currentPage,
    pageSize: searchParams.pageSize
  }
  pageLoading.value = true
  await accountListPage(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
      searchParams.total = res.page.totalSize
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取项目树表格数据
const getProjectData = async () => {
  pageLoading.value = true
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.account-manage-page
  height 100%
  .box-card
    height 100%
    &:deep(.el-card__body)
      height 100%
      position relative
      box-sizing border-box
  .table-block
    top 152px
</style>
